<template>
  <div v-loading="isLoadingData">
    <el-row>
      <el-col :span="24">
        <el-input
          v-model="search[0].value"
          placeholder="搜索"
          class="input-with-select"
          @keyup.enter="refreshMemberList"
        >
          <template #prepend>
            <el-select
              v-model="search[0].type"
              class="el-select"
              style="width: 140px"
            >
              <el-option label="搜索ID" value="0"></el-option>
              <el-option label="搜索名称" value="1"></el-option>
              <el-option label="搜索邮箱" value="2"></el-option>
              <el-option label="搜索登录IP" value="4"></el-option>
            </el-select>
          </template>
          <template #append>
            <el-button @click="refreshMemberList" icon="Search" />
          </template>
        </el-input>
      </el-col>

      <el-col :span="24">
        <el-select
          clearable
          v-model="search[1].value"
          class="el-select"
          style="width: 140px"
          placeholder="选择头衔"
        >
          <el-option
            v-for="(role, index) in userInfo.role_list"
            :key="index"
            :label="role.name"
            :value="role.id"
          ></el-option>
        </el-select>
        <el-select
          clearable
          v-model="search[2].value"
          class="el-select"
          style="width: 140px"
          placeholder="选择状态"
        >
          <el-option label="封禁" value="0"></el-option>
          <el-option label="正常" value="1"></el-option>
        </el-select>
      </el-col>
    </el-row>

    <el-table :data="member_list" stripe style="width: 100%; height: 100%">
      <el-table-column prop="id" width="60" label="ID" />
      <el-table-column prop="account" label="账号" width="120" />
      <el-table-column prop="nickname" label="昵称" width="120">
        <template #default="scope">
          {{ member_list[scope.$index].nickname }}
          <UserRole :role="member_list[scope.$index].role_list" />
        </template>
      </el-table-column>
      <el-table-column prop="reg_time" label="注册时间" width="180" />
      <el-table-column
        prop="last_login_time"
        label="最后登录时间"
        width="180"
      />
      <el-table-column prop="last_login_ip" label="最后登录IP" width="120" />
      <el-table-column prop="stat" label="状态" width="80">
        <template #default="scope">
          <el-tag
            :type="member_list[scope.$index].stat == 0 ? 'danger' : '正常'"
            size="small"
          >
            {{ member_list[scope.$index].stat == 0 ? '封禁' : '正常' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="120" />
      <el-table-column prop="remark" label="备注" width="120" />
      <el-table-column label="操作" fixed="right">
        <template #default="scope">
          <el-button
            size="small"
            link
            type="danger"
            @click="showLockItem(scope.$index)"
          >
            <div v-if="member_list[scope.$index].stat == 0">解锁</div>
            <div v-else>锁定</div>
          </el-button>
          <el-button
            size="small"
            link
            type="primary"
            @click="showSetUserRole(scope.$index)"
            >头衔设置</el-button
          >
          <el-button
            size="small"
            link
            type="primary"
            @click="showSetUserInfo(scope.$index)"
            >修改信息</el-button
          >
          <el-button
            size="small"
            link
            type="primary"
            @click="toUserIndex(member_list[scope.$index].id)"
            >查看主页</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
  <el-pagination
    v-model:current-page="page"
    background
    :page-size="limit"
    layout="prev, pager, next, jumper"
    :total="total"
    style="margin: 2rem 0"
  />

  <!--锁定账号弹窗-->
  <dialog-confirm
    title="提示"
    v-model:visible="dialogShow.lockAccount"
    :loading="isLocking"
    @submit="lockItem(1)"
  >
    <span>
      <span v-if="activeItem.stat == 1"
        >是否锁定账号[ID:{{ activeItem.id }}]</span
      >
      <span v-else>是否解锁账号[ID:{{ activeItem.id }}]</span>
      <span style="color: #008ac5">{{ activeItem.account }}</span>
    </span>
  </dialog-confirm>

  <!--头衔设置弹窗-->
  <dialog-confirm
    title="头衔设置"
    v-model:visible="dialogShow.setRole"
    @submit="setUserRole"
  >
    <el-form>
      <el-form-item label="头衔列表">
        <el-row>
          <el-tag
            @click="addUserRole(x)"
            v-for="x in role_list"
            :color="x.color"
            :type="x.type"
            :effect="x.effect"
          >
            {{ x.name }}
          </el-tag>
        </el-row>
      </el-form-item>
      <el-form-item label="已选择">
        <el-row>
          <el-tag
            @click="removeUserRole(x)"
            v-for="x in user_role_list"
            :color="x.color"
            :type="x.type"
            :effect="x.effect"
          >
            {{ x.name }}
          </el-tag>
        </el-row>
      </el-form-item>
    </el-form>
  </dialog-confirm>
  <!--修改备注弹窗-->
  <dialog-confirm
    title="修改信息，按需填入"
    v-model:visible="dialogShow.setRemark"
    :loading="isLocking"
    @submit="setEdit()"
  >
    <span> 修改头像 </span>
    <UserIcon
      class="item-top-title-list avatar"
      v-if="edit.avatar != ''"
      :src="edit.avatar"
      :alt="edit.nickname"
    />
    <el-input type="text" v-model="edit.avatar"></el-input>
    <span> 修改背景 </span>
    <el-image
      fit="contain"
      v-if="edit.background"
      :src="edit.background"
    ></el-image>
    <el-input type="text" v-model="edit.background"></el-input>
    <span> 修改邮箱 </span>
    <el-input
      type="email"
      maxlength="255"
      show-word-limit
      v-model="edit.email"
    ></el-input>
    <span> 修改昵称 </span>
    <el-input type="name" v-model="edit.nickname"></el-input>
    <span> 修改密码 </span>
    <el-input
      type="password"
      maxlength="16"
      show-word-limit
      v-model="edit.newPass"
    ></el-input>
    <span> 修改签名 </span>
    <el-input
      type="textarea"
      maxlength="255"
      show-word-limit
      v-model="edit.signature"
    ></el-input>

    <span> 请输入备注内容 </span>
    <el-input
      type="textarea"
      maxlength="255"
      show-word-limit
      v-model="edit.remark"
    ></el-input>
  </dialog-confirm>
</template>

<script lang="ts">
import Method from '@/globalmethods.ts'
import DialogConfirm from '@comps/dialogs/confirm.vue'
import UserIcon from '@comps/user/userIcon.vue'
import Cfg from '../../../config/config'
import UserRole from '@comps/user/roleList.vue'
import { ElMessage } from 'element-plus'
import { watch } from 'vue'
import { memberItem, roleItem, res } from '../type.ts'

export default {
  name: 'admin-account',
  components: { UserIcon, DialogConfirm, UserRole },
  data() {
    return {
      userInfo: Cfg.userInfo,
      page: 1,
      limit: 10,
      total: 0,
      isLoadingData: false,
      isLocking: false,
      isInjecting: false,
      isPassing: false,
      search: [
        {
          value: '',
          type: '1',
        },
        {
          value: '',
          type: '5', // 等级
        },
        {
          value: '',
          type: '3', // 状态
        },
      ],

      dialogShow: {
        lockAccount: false,
        setRemark: false, //设置备注弹窗
        setRole: false, //头衔设置弹窗
      },
      edit: {
        remark: '',
        nickname: '',
        email: '',
        avatar: '',
        signature: '',
        background: '',
        newPass: '',
      },
      member_list: <memberItem[]>[],
      activeItem: <memberItem>{},
      role_list: <roleItem[]>[],
      user_role_list: <roleItem[]>[],
    }
  },
  methods: {
    toUserIndex(id: number) {
      this.$router.push(`/user/${id}`)
    },
    setEdit() {
      Method.api_post('/admin/edit_user', {
        id: this.activeItem.id,
        ...this.edit,
      }).then((res: any) => {
        let data = res.data
        if (data.code == 200) {
          this.dialogShow.setRemark = false
          this.member_list[this.activeItem.id - 1].remark = this.edit.remark
          ElMessage({
            type: 'success',
            message: '修改成功',
          })
        } else {
          ElMessage({
            type: 'error',
            message: '修改失败',
          })
        }
      })
    },
    showLockItem(index: number) {
      this.dialogShow.lockAccount = true
      this.activeItem = this.member_list[index]
    },
    showSetUserRole(index: number) {
      this.dialogShow.setRole = true
      this.activeItem = this.member_list[index]
      let list = Method.decodeRoleList(this.activeItem.role_list)
      this.user_role_list = Method.copyObject(list)
      this.refreshRoleList()
    },
    showSetUserInfo(index: number) {
      this.dialogShow.setRemark = true
      this.activeItem = this.member_list[index]
    },
    lockItem(type: number) {
      this.isLocking = true
      let id = 0
      let stat = 0
      id = this.activeItem.id
      stat = this.activeItem.stat == 1 ? 0 : 1
      Method.api_post('/admin/lock_item', {
        type: type,
        id: id,
        stat: stat,
      }).then((response) => {
        this.isLocking = false
        let res = <res>response.data
        if (res.code == 200) {
          this.activeItem.stat = res.data.stat
          this.dialogShow.lockAccount = false
          ElMessage(res.data.stat === 0 ? '锁定成功' : '解锁成功')
        }
      })
    },
    /**
     * 搜索用户
     */
    refreshMemberList() {
      this.isLoadingData = true
      let payLoad = {
        page: this.page,
        limit: this.limit,
        conditions: this.search
          .map((x: any) => {
            if (x.value !== '') {
              x.type = Number(x.type)
              return x
            }
          })
          .filter(Boolean),
      }
      Method.api_post('/admin/member_list', payLoad)
        .then((response) => {
          this.isLoadingData = false
          let res = response.data
          if (res.code == 200) {
            if (this.page == 1) this.total = res.sum
            res.data.forEach((x: any) => {
              x.last_login_time = Method.formatNormalTime(x.last_login_time)
              x.reg_time = Method.formatNormalTime(x.reg_time)
            })
            this.member_list = res.data
          }
        })
        .catch(() => {
          this.isLoadingData = false
          ElMessage({
            type: 'error',
            message: '请求错误',
          })
        })
    },
    refreshRoleList() {
      this.isLoadingData = true
      let payLoad = {
        all: 1,
      }
      Method.api_post('/admin/role_list', payLoad).then((response) => {
        this.isLoadingData = false
        let res = response.data
        if (res.code == 200) {
          this.role_list = res.data as roleItem[]
        }
      })
    },
    setUserRole() {
      let list = <number[]>[]
      this.user_role_list.forEach((x: any) => {
        list.push(x.id)
      })
      this.isLocking = true
      Method.api_post('/admin/set_user_role', {
        uid: this.activeItem.id,
        role_list: JSON.stringify(list),
      }).then((response) => {
        this.isLocking = false
        let res = <res>response.data
        if (res.code == 200) {
          ElMessage('设置成功')
          this.dialogShow.setRole = false
          this.refreshMemberList()
        } else ElMessage(res.msg)
      })
    },
    addUserRole(x: roleItem) {
      this.user_role_list.push(x)
    },
    removeUserRole(x: roleItem) {
      this.user_role_list.splice(this.user_role_list.indexOf(x), 1)
    },
  },
  mounted() {
    this.search[0].value =
      (this.$route.query.search as string) ?? this.search[0].value
    this.search[0].type =
      (this.$route.query.search_type as string) ?? this.search[0].type

    this.refreshMemberList()
    this.role_list = []
    watch(
      () => this.page,
      () => {
        this.refreshMemberList()
      },
    )

    watch(
      () => this.$route,
      () => {
        if (this.$route.query.search_type && this.$route.query.search) {
          this.search[0].value = this.$route.query.search as string
          this.search[0].type = this.$route.query.search_type as string
          this.refreshMemberList()
        }

        // this.$router.push({
        // path: '/admin',
        // query: this.$route.query,
        // })
      },
    )
  },
}
</script>
